const Connection = require('ssh2').Client
const client = require('scp2')
const path = require('path')
const fs = require('fs')
const minimist = require('minimist')
const remoteInfo = {
  host: '172.25.4.209',
  username: 'root',
  password: 'XHCJ_456rtyfgh&*g',
}
const port = 22
const remotePath = '/usr/local/nginx/html/web/cnfic'
const argv = minimist(process.argv.slice(2))
const { projectName } = argv
console.log('projectName', projectName)
//读取version.json
const version = require('./version.json')
const { [projectName]: number = 0 } = version
const date = new Date().toISOString().split('T')[0].split('-').join('')
//serviceVersion : 日期+number：20250114.1
const serviceVersion = `${date}.${number}`
const d_name = projectName
const assetsRoot = path.resolve(__dirname, '../dist/' + d_name)
const serverRoot = remotePath + '/' + d_name
const command = `mv ${remotePath}/${d_name} ${remotePath}/${d_name}${serviceVersion && '-' + serviceVersion}`
projectName && execShell(command).then(deployProject)
//修改文件名
function execShell(command) {
  return new Promise((resolve, reject) => {
    const conn = new Connection()
    conn
      .on('ready', function () {
        conn.shell(function (err, stream) {
          if (err) throw err
          stream
            .on('close', function () {
              conn.end()
              resolve()
            })
            .on('data', function (data) {
              console.log('STDOUT: ' + data)
            })
            .stderr.on('data', function (data) {
              reject(data)
            })
          stream.end(command + '\nexit\n')
        })
      })
      .connect({
        ...remoteInfo,
        port,
      })
  })
}

//上传部署文件
function deployProject() {
  console.log('正在上传目录:' + assetsRoot + '   到:' + serverRoot)
  client.scp(
    assetsRoot,
    {
      ...remoteInfo,
      path: serverRoot,
    },
    function (err) {
      if (err) {
        console.log(err)
      } else {
        console.log(' 上传成功')
        //修改version.json
        version[projectName] = number + 1
        console.log('version', version)
        fs.writeFileSync(
          path.resolve(__dirname, './version.json'),
          JSON.stringify(version, null, 2)
        )
      }
    }
  )
}
